package com.example.myapplication.ui.gallery;

import android.net.ConnectivityManager;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.MyItemRecyclerViewAdapter;
import com.example.myapplication.databinding.FragmentGalleryBinding;

import java.net.Inet4Address;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    final ConnectivityManager.NetworkCallback networkCallback[] = new ConnectivityManager.NetworkCallback[1];
    ExecutorService service = Executors.newCachedThreadPool();
    String ipLoopback;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);

        binding = FragmentGalleryBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textView;
        galleryViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);

        binding.discoveryList.setLayoutManager(new LinearLayoutManager(getContext()));
        galleryViewModel.getObjects().observe(getViewLifecycleOwner(), list -> binding.discoveryList.setAdapter(new MyItemRecyclerViewAdapter(list)));

        if (networkCallback[0] == null) {

            service.submit(() -> {
                final NetworkRequest request =
                        new NetworkRequest.Builder()
                                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                                .build();

                final ConnectivityManager connectivityManager =
                        getContext().getSystemService(ConnectivityManager.class);

                networkCallback[0] = new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
                        linkProperties.getLinkAddresses().stream()
                                .map(LinkAddress::getAddress)
                                .filter(Objects::nonNull)
                                .filter(Inet4Address.class::isInstance)
                                .map(Inet4Address.class::cast)
                                .map(Inet4Address::getHostAddress)
                                .findFirst().ifPresent(galleryViewModel::discoverNetworkOf);
                        connectivityManager.unregisterNetworkCallback(networkCallback[0]);
                    }
                };
                connectivityManager.requestNetwork(request, networkCallback[0]);
                connectivityManager.registerNetworkCallback(request, networkCallback[0]);
            });

        }

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public void onSelectHome(View view) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);
        galleryViewModel.postLog("selected");
    }
}